'use strict';
const { Model } = require('sequelize');
const moment = require('moment/moment');
moment.locale('zh-cn');
const { Conflict } = require('http-errors');
module.exports = (sequelize, DataTypes) => {
  class Chapter extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Chapter.belongsTo(models.Course, { as: 'course' });
    }
  }
  Chapter.init(
    {
      courseId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: '课程ID必须填写' },
          notEmpty: { msg: '课程ID不能为空' },
          async isPresent(value) {
            const category = await sequelize.models.Course.findByPk(value);
            if (!category) {
              throw new Conflict(`ID为: ${value} 的课程不存在`);
            }
          },
        },
      },
      title: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: '章节名必须填写' },
          notEmpty: { msg: '章节名不能为空' },
          async isPresent(value) {
            const title = await Chapter.findOne({ where: { title: value } });
            if (title) {
              throw new Conflict(`章节为: ${value} 的标题已存在`);
            }
          },
        },
      },
      content: DataTypes.TEXT,
      video: {
        type: DataTypes.STRING,
        // validate: {
        //   isUrl: { msg: '视频地址不正确' }
        // }
      },
      rank: DataTypes.INTEGER,
      free: {
        type: DataTypes.BOOLEAN,
        validate: {
          isIn: { args: [[true, false]], msg: '是否免费课程的值必须是，推荐true 不推荐false' },
        },
      },
      createdAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue('createdAt')).format('LL');
        },
      },
      updatedAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue('updatedAt')).format('LL');
        },
      },
    },
    {
      sequelize,
      modelName: 'Chapter',
    }
  );
  return Chapter;
};
